package com.lushixiang.filter;

import com.lushixiang.token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;


@Order(1)
@Slf4j
@WebFilter(filterName = "BaseFilter", urlPatterns = "/*" )
        //initParams = {@WebInitParam(name = "URL", value = "http://localhost:8080")})
public class BaseFilter implements Filter{
    // 白名单 允许访问
    private final List<String> passPath= Arrays.asList("/","/signIn","/signUp/applyEmailAddrCheck","/signUp/commit","/applyResetPassword","/resetPassword","/signUp/resetPassword","/user/deregistration");

    Pattern pattern = Pattern.compile("http://lushixiang.com/static/.*");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");

        log.info("请求路径：{}",request.getRequestURI());
        if(passPath.contains(request.getRequestURI())|| pattern.matcher(request.getRequestURI()).matches()){
            log.info("允许访问：token:{}",token);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if(token != null && TokenUtil.verifyToken(token)){
            log.info("token: {}不为null，并且通过验证",token);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        log.info("token不通过");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json");
        response.getWriter().write("{\"resHead\": { \"resCode\": \"/signIn"+"\", \"resMsg\": \"3001"+"\" },\"resBody\": null}");
    }
}
